import { ref, reactive } from 'vue'
import request from '@/utils/request'

// 全局用户状态
const userInfo = reactive({
  isLoggedIn: false,
  id: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  gender: '',
  bio: ''
})

const loading = ref(false)

// 获取用户信息
async function fetchUserInfo() {
  if (loading.value) return // 防止重复请求
  
  try {
    loading.value = true
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    
    if (!token) {
      resetUserInfo()
      return
    }

    const response = await request.get('/user/info')
    const data = response.data
    
    if (data && data.code === 0 && data.data) {
      Object.assign(userInfo, {
        isLoggedIn: true,
        id: data.data.id,
        username: data.data.username || '',
        nickname: data.data.nickname || data.data.username || '',
        email: data.data.email || '',
        phone: data.data.phone || '',
        avatar: data.data.avatar || '',
        gender: data.data.gender || '',
        bio: data.data.bio || ''
      })
      
      console.log('用户信息获取成功:', data.data)
    } else {
      // Token可能过期，清除并设为未登录状态
      clearTokens()
      resetUserInfo()
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    
    // 如果是401错误，说明token无效，清除token
    if (error.response && error.response.status === 401) {
      clearTokens()
      resetUserInfo()
    }
  } finally {
    loading.value = false
  }
}

// 清除tokens
function clearTokens() {
  localStorage.removeItem('token')
  sessionStorage.removeItem('token')
}

// 重置用户信息
function resetUserInfo() {
  Object.assign(userInfo, {
    isLoggedIn: false,
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    avatar: '',
    gender: '',
    bio: ''
  })
}

// 退出登录
function logout() {
  clearTokens()
  resetUserInfo()
}

// 显示用户名：优先显示昵称，其次用户名
function getDisplayName() {
  return userInfo.nickname || userInfo.username || '用户'
}

// 检查登录状态
function checkAuthStatus() {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (token && !userInfo.isLoggedIn) {
    fetchUserInfo()
  } else if (!token) {
    resetUserInfo()
  }
}

export function useAuth() {
  return {
    userInfo,
    loading,
    fetchUserInfo,
    logout,
    getDisplayName,
    checkAuthStatus,
    resetUserInfo,
    clearTokens
  }
} 